package utils

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/bzsome/ChaoGoDown/chaoDown"
)

func CreateDir(dir string) error {
	//创建下载目录文件夹
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		if err := os.Mkdir(dir, os.ModePerm); err != nil {
			return err
		}
	}
	return nil
}

func MergeFile(fileArr []string, savePath string) error {
	outFile, openErr := os.OpenFile(savePath, os.O_CREATE|os.O_WRONLY, 0600)
	if openErr != nil {
		fmt.Printf("Can not open file %s", savePath)
	}
	bWriter := bufio.NewWriter(outFile)

	for _, fileName := range fileArr {
		fp, fpOpenErr := os.Open(fileName)
		if fpOpenErr != nil {
			fmt.Printf("Can not open file %v", fpOpenErr)
			return fpOpenErr
		}
		bReader := bufio.NewReader(fp)
		for {
			buffer := make([]byte, 1024)
			readCount, readErr := bReader.Read(buffer)
			if readErr == io.EOF {
				break
			} else {
				bWriter.Write(buffer[:readCount])
			}
		}
	}
	bWriter.Flush()
	return nil
}

//调用下分区下载器，且支持断点续传
func DownChuckUrl(url string, savePath string, fileName string, poolSize int, chuckSize int64) (*chaoDown.Downloader, error) {
	request := &chaoDown.Request{
		Method: "get",
		URL:    url,
	}
	download := &chaoDown.Downloader{
		PoolSize:  poolSize,
		ChuckSize: chuckSize,
		Path:      savePath,
		FileName:  fileName,
		Wait:      true,
	}

	return download, download.Down(request)
}

func FilenameByUri(uri string) string {
	start := strings.LastIndex(uri, "/") + 1
	return uri[start:]
}
